#include "continue.h"
#include <boost/lexical_cast.hpp>
#include <boost/dynamic_bitset.hpp>
#include <iostream>
#include <fstream>
using namespace std;

cget::Continue::Continue(Config& c) {

	url = c.getConfig(c_url);
	host = c.getConfig(c_host);
	protocol = c.getConfig(c_protocol);
	port = c.getConfig(c_port);
	path = c.getConfig(c_path);
	filename = c.getConfig(c_filename);

	try {
		filesize = boost::lexical_cast<size_t>(c.getConfig(c_filesize));

	} catch(boost::bad_lexical_cast& e) {
		throw string("cast filesize failed");
	}

	if(filesize < 1024) {
		num_block = 1;
	}
	else if(filesize >= 1024 && filesize < 1024*1024) {
		num_block = 20;
	}
	else if(filesize >= 1024*1024 && filesize < 1024*1024*100) {
		num_block = 100;
	}
	else {
		num_block = 1000;
	}

	bs = dynamic_bitset_ptr(new boost::dynamic_bitset<>(num_block));

}
	
cget::Continue::Continue(const string& cont_file) {
	//cout << "from file" << endl;
	
	ifstream ifs(cont_file.c_str());
	
	getline(ifs,url);
	getline(ifs,host);
	getline(ifs,protocol);
	getline(ifs,port);
	getline(ifs,path);
	getline(ifs,filename);

	ifs >> filesize >> num_block;
	string m;
	ifs >> m;

	bs = dynamic_bitset_ptr(new boost::dynamic_bitset<>(m));
	ifs.close();
}

void cget::Continue::sync() {
	
	string cont_file = filename + ".c-get";

	ofstream ofs(cont_file.c_str());

	ofs << url << endl;
	ofs << host << endl;
	ofs << protocol << endl;
	ofs << port << endl;
	ofs << path << endl;
	ofs << filename << endl;
	ofs << filesize << endl;
	ofs << num_block << endl;
	ofs << *bs << endl;

	ofs.close();

}
